include("${CMAKE_CURRENT_LIST_DIR}/../../ohos-ndk-finder.cmake")

set(CMAKE_SYSTEM_NAME OHOS CACHE STRING "")
set(OHOS_PLATFORM OHOS CACHE STRING "")

set(NDK_PATH "")
set(NDK_VERSION "")
find_ohos_ndk(NDK_PATH NDK_VERSION)

if(NOT EXISTS "${NDK_PATH}/build/cmake/ohos.toolchain.cmake")
    message(FATAL_ERROR "Could not find OHOS toolchain at ${NDK_PATH}/build/cmake/ohos.toolchain.cmake")
endif()

message(STATUS "Using OHOS NDK: ${NDK_PATH}")

if (VCPKG_TARGET_TRIPLET MATCHES "x64-ohos")
    set(OHOS_ARCH x86_64 CACHE STRING "")
elseif (VCPKG_TARGET_TRIPLET MATCHES "arm64-ohos")
    set(OHOS_ARCH arm64-v8a CACHE STRING "")
elseif (VCPKG_TARGET_TRIPLET MATCHES "arm-ohos")
    set(OHOS_ARCH armeabi-v7a CACHE STRING "")
else()
    message(FATAL_ERROR "Unknown ABI for target triplet ${VCPKG_TARGET_TRIPLET}")
endif()

set(ENV{CMAKE_OHOS_NDK} ${NDK_PATH})
include("${NDK_PATH}/build/cmake/ohos.toolchain.cmake")

if(NOT _VCPKG_OHOS_TOOLCHAIN)
    set(_VCPKG_OHOS_TOOLCHAIN 1)

    if(POLICY CMP0056)
        cmake_policy(SET CMP0056 NEW)
    endif()
    if(POLICY CMP0066)
        cmake_policy(SET CMP0066 NEW)
    endif()
    if(POLICY CMP0067)
        cmake_policy(SET CMP0067 NEW)
    endif()
    if(POLICY CMP0137)
        cmake_policy(SET CMP0137 NEW)
    endif()
    list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES
        VCPKG_CRT_LINKAGE VCPKG_TARGET_ARCHITECTURE
        VCPKG_C_FLAGS VCPKG_CXX_FLAGS
        VCPKG_C_FLAGS_DEBUG VCPKG_CXX_FLAGS_DEBUG
        VCPKG_C_FLAGS_RELEASE VCPKG_CXX_FLAGS_RELEASE
        VCPKG_LINKER_FLAGS VCPKG_LINKER_FLAGS_RELEASE VCPKG_LINKER_FLAGS_DEBUG
    )

    string(APPEND CMAKE_C_FLAGS " -fPIC ${VCPKG_C_FLAGS} ")
    string(APPEND CMAKE_CXX_FLAGS " -fPIC ${VCPKG_CXX_FLAGS} ")
    string(APPEND CMAKE_C_FLAGS_DEBUG " ${VCPKG_C_FLAGS_DEBUG} ")
    string(APPEND CMAKE_CXX_FLAGS_DEBUG " ${VCPKG_CXX_FLAGS_DEBUG} ")
    string(APPEND CMAKE_C_FLAGS_RELEASE " ${VCPKG_C_FLAGS_RELEASE} ")
    string(APPEND CMAKE_CXX_FLAGS_RELEASE " ${VCPKG_CXX_FLAGS_RELEASE} ")

    string(APPEND CMAKE_MODULE_LINKER_FLAGS " ${VCPKG_LINKER_FLAGS} ")
    string(APPEND CMAKE_SHARED_LINKER_FLAGS " ${VCPKG_LINKER_FLAGS} ")
    string(APPEND CMAKE_EXE_LINKER_FLAGS " ${VCPKG_LINKER_FLAGS} ")
    string(APPEND CMAKE_MODULE_LINKER_FLAGS_DEBUG " ${VCPKG_LINKER_FLAGS_DEBUG} ")
    string(APPEND CMAKE_SHARED_LINKER_FLAGS_DEBUG " ${VCPKG_LINKER_FLAGS_DEBUG} ")
    string(APPEND CMAKE_EXE_LINKER_FLAGS_DEBUG " ${VCPKG_LINKER_FLAGS_DEBUG} ")
    string(APPEND CMAKE_MODULE_LINKER_FLAGS_RELEASE " ${VCPKG_LINKER_FLAGS_RELEASE} ")
    string(APPEND CMAKE_SHARED_LINKER_FLAGS_RELEASE " ${VCPKG_LINKER_FLAGS_RELEASE} ")
    string(APPEND CMAKE_EXE_LINKER_FLAGS_RELEASE " ${VCPKG_LINKER_FLAGS_RELEASE} ")
endif()
